import requests
from bs4 import BeautifulSoup
import urllib.parse
import random

class WeatherTools():

    @staticmethod
    def get_temperature_from_bing(city):
        """
        尝试从百度天气页面获取指定城市的当前气温。

        :param city: 城市名称
        :return: 当前气温（摄氏度），如果失败则返回None
        """
        # 百度天气页面的URL，需要替换城市名称
        params = {'wd':f'{city} 天气',
                  'rsv_pq':'ade87f0b001814e4',
                  'rqlang':'cn'}
        encoded_params = urllib.parse.urlencode(params)
        url = f"https://www.baidu.com/s?" + encoded_params

        headers_choices = [
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.6'
        ]

        headers = {'User-Agent' : random.choice(headers_choices)}
        print(headers)
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            # print( response.text )
            # 解析网页内容
            soup = BeautifulSoup(response.text, 'html.parser')
            # 尝试找到包含气温的元素，这里的选择器需要根据实际页面结构进行调整
            temp_element = soup.find('div', {'class': 'weather-main-temp_6CEpK'})
            if temp_element:
                # 获取气温文本
                temperature = temp_element.text.strip()
                return temperature
            else:
                return "无法获取"


    # 测试代码
    @staticmethod
    def test_get_temperature_from_bing():
        city = "上海"
        temperature = WeatherTools.get_temperature_from_bing(city)
        if temperature:
            print(f"The current temperature in {city} is {temperature}.")
        else:
            print("Failed to get the current temperature.")
        return temperature

if __name__ == '__main__':
    # 运行测试
    t = WeatherTools.test_get_temperature_from_bing()
    print(t)